package com.example.userservice.services;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;

public class CompletableFutureDemo {
    public static void main(String[] args) throws InterruptedException {
        long l = System.currentTimeMillis();
        CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println("在回调中执行耗时操作...");
            long l1 = System.currentTimeMillis();
            timeConsumingOperation();
            long l2 = System.currentTimeMillis();
            System.out.println("在回调耗时..."+(l2 - l1));
            return 100;
        });
        completableFuture = completableFuture.thenCompose(i -> {
            return CompletableFuture.supplyAsync(() -> {
                System.out.println("在回调的回调中执行耗时操作...");
                long l1 = System.currentTimeMillis();
                timeConsumingOperation2();
                long l2 = System.currentTimeMillis();
                System.out.println("在回调的回调中耗时..."+(l2 - l1));
                return i + 100;
            });
        });//<1>

//        completableFuture.whenComplete((result,e)->{
//            long l1 = System.currentTimeMillis();
//            System.out.println("whenComplete:" + result);
//            long l2 = System.currentTimeMillis();
//            System.out.println("完成耗时..."+(l2 - l1));
//        });
        System.out.println("主线程运算耗时:" + (System.currentTimeMillis() - l) + " ms");
        new CountDownLatch(1).await();
    }

    static void timeConsumingOperation() {
        try {
            Thread.sleep(3000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    static void timeConsumingOperation2() {
        try {
            Thread.sleep(4000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
